<template>
  <div>
    <Modal
      v-model="showModel"
      :title="modelTitle"
      :loading="loading"
      @on-ok="saveModel"
      @on-cancel="closeModel"
      :mask-closable="false"
      :width="700"
    >
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120">
        <div class="form-gourp">
          <span class="form-title">基础信息</span>
          <FormItem label="名称" prop="contestName" v-if="!isRestart" key="contestName">
            <Input
              v-model.trim="formValidate.contestName"
              :maxlength="128"
              placeholder='不能包含下列任意英文字符 \ / : * ? " < > |，长度为1-128个字符'
            />
          </FormItem>
          <FormItem label="比赛状态" prop="activityStatus" v-if="!isRestart" key="activityStatus">
            <Select filterable v-model="formValidate.activityStatus" placeholder="请选择比赛状态" disabled>
              <Option value="0">准备中</Option>
              <Option value="1">进行中</Option>
              <Option value="2">已结束</Option>
            </Select>
          </FormItem>
          <FormItem label="比赛时间" prop="Dates" key="Dates">
            <DatePicker
              :editable="false"
              type="datetimerange"
              :value="formValidate.Dates"
              format="yyyy-MM-dd HH:mm"
              placement="bottom-end"
              confirm
              ref="datePicker"
              placeholder="选择日期"
              @on-ok="clickOkBtn"
              @on-clear="clickClearBtn"
              @on-open-change="switchOpenChange"
              @on-change="changeDates"
              :options="disabledOptions"
              style="width: 280px"
            ></DatePicker>
            <p style="color:#ff9900;font-size:10px;line-height: 2;">
              <Icon type="ios-information-circle-outline" />
              选择同一天的时间段，请先双击要选择的日期
            </p>
            <p style="color:#ff9900;font-size:10px;line-height: 2;">
              <Icon type="ios-information-circle-outline" />
              开始时间不能小于当前时间
            </p>
          </FormItem>
          <FormItem label="描述" prop="description" v-if="!isRestart" key="description">
            <Input
              v-model.trim="formValidate.description"
              type="textarea"
              :maxlength="200"
              :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入描述信息"
            />
          </FormItem>
          <FormItem label="比赛图片" prop="iconPath" v-if="!isRestart">
            <section>
              <Row>
                <Col span="24">
                  <Upload
                    ref="upload"
                    :action="uploadAction"
                    :show-upload-list="false"
                    :format="['jpg', 'jpeg', 'png']"
                    :on-format-error="handleFormatError"
                    :on-success="getImageUrl"
                    :before-upload="handleBeforeUpload"
                    :headers="uploadHeader"
                  >
                    <Button icon="ios-cloud-upload-outline">上传图片</Button>
                    <img
                      :src="iconSrc"
                      style="width:auto;height:40px;margin-left: 30px;vertical-align: middle;"
                      v-if="formValidate.iconPath"
                    />
                    <!-- <WarningTip content="请上传jpg，jpeg，png格式图片"></WarningTip> -->
                    <span style="color:#f90; position: absolute; top: 30px; left: 0;">
                      <Icon type="ios-information-circle-outline" />支持jpg,jpeg,png格式图片</span
                    >
                  </Upload>
                  <p v-if="showTip" style="color:red; position: relative; top: 24px;">
                    请上传jpg，jpeg，png格式图片
                  </p>
                  <div class="ivu-form-item-error-tip" v-if="uploaderror">请上传图片</div>
                </Col>
              </Row>
            </section>
          </FormItem>
        </div>
        <div class="form-gourp">
          <span class="form-title">竞赛模式</span>
          <FormItem label="是否立即显示成绩" prop="needRelease" key="needRelease">
            <RadioGroup v-model="formValidate.needRelease">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </RadioGroup>
            <span style="color:#ff9900;font-size:10px;line-height: 2;">
              <Icon type="ios-information-circle-outline" />
              {{
                formValidate.needRelease === 1
                  ? '实验员答题结束后可立即查看成绩'
                  : '设计师发布成绩后，实验员方可查看成绩'
              }}
            </span>
          </FormItem>
        </div>
      </Form>
    </Modal>
  </div>
</template>

<script>
import encryption from '@/libs/encryption.js';
import usally from '@/mixin/usally';
import { addcompetition, modifycompetition } from '@/api/competition';
import { parseJson } from '@/libs/utils';
import {validateName128 } from '@/libs/reg.js'

export default {
  name: 'knowledgeModel',
  props: [],
  mixins: [usally],
  data() {
    const validateName = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp('^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$');
      //验证警戒值
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('请输入中文、数字、字母、下划线、中划线'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    // 验证时间选择是否正确
    const validateDate = (rule, value, callback) => {
      if (value) {
        if (Array.isArray(value) && value.length < 2) {
          callback(new Error('请选择开始与结束时间'));
        } else if (value[0] === '' || value[1] === '') {
          callback(new Error('请选择开始与结束时间'));
        } else if (new Date(value[0]).getTime() < new Date().getTime()) {
          callback(new Error('开始时间必须大于当前时间'));
        } else if (new Date(value[1]).getTime() - new Date(value[0]).getTime() <= 0) {
          callback(new Error('开始时间必须小于结束时间'));
        } else {
          callback();
        }
      } else {
        callback(new Error('请选择开始与结束时间'));
      }
    };
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    return {
      isClickOkBtn: false, // 是否点击了DatePicker组件的确认按钮
      originalTime: [], // 展示DatePicker组件时的初始时间
      showModel: false,
      loading: true,
      modelTitle: '创建知识赛',
      type: 1,
      isRestart: false, //是否是重新开始，重新开始只显示时间
      formValidate: {
        needRelease: 1,
        contestName: '',
        difficulty: '0',
        activityStatus: '0',
        description: '',
        iconPath: '',
        startDate: '',
        endDate: '',
        Dates: []
      },
      ruleValidate: {
        needRelease: [
          {
            type: 'number',
            required: true,
            message: '请选择是否立即显示成绩',
            trigger: 'change'
          }
        ],
        contestName: [
          {
            required: true,
            max: 128,
            message: '知识赛名称长度为1-128个字符',
            trigger: 'change'
          },
          { validator: validateName128, trigger: 'change' }
        ],
        difficulty: [
          {
            required: true,
            message: '请选择竞赛难度',
            trigger: 'change'
          }
        ],
        activityStatus: [
          {
            required: true,
            message: '请选择竞赛状态',
            trigger: 'change'
          }
        ],
        Dates: [
          { required: true, type: 'array', message: '不能为空', trigger: 'change' },
          { validator: validateDate, trigger: 'change' }
        ]
      },
      uploadAction: '/api/minio/upload/permanent?visibility=company&type=images&bucket=images',
      uploadHeader: {
        Authorization: localStorage.token,
        Accept: '*/*'
      },
      iconSrc: '',
      showTip: false,
      uploaderror: false,
      startDates: '',
      endDates: '',
      disabledOptions: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      }
    };
  },
  methods: {
    initModel() {
      this.$refs.formValidate.resetFields();
      this.closeModel();
      this.showModel = true;
      this.formValidate = {
        needRelease: 1,
        contestName: '',
        difficulty: '0',
        activityStatus: '0',
        description: '',
        iconPath: '',
        startDate: '',
        endDate: '',
        Dates: []
      };
      this.iconSrc = '';
      this.showTip = false;
      this.uploaderror = false;
    },
    openModel(modelObj, isRestart) {
      //type,接收是否是重新开始
      this.isRestart = isRestart;
      this.initModel();
      if (modelObj) {
        this.formValidate = { ...modelObj, Dates: [modelObj.startDate, modelObj.endDate] };
        let extension = parseJson(modelObj.extension);
        this.$set(
          this.formValidate,
          'needRelease',
          extension.needRelease === undefined ? 1 : extension.needRelease
        );
        this.type = 2;
        this.modelTitle = '修改知识赛';
        if (modelObj.iconPath) {
          let src = modelObj.iconPath; //.slice(1);
          this.iconSrc = `../../Learn/${src}`;
          //this.iconSrc = `http://172.18.100.1/Learn/${src}`;
        }
        this.startTimeChange(this.formValidate.Dates);
      } else {
        this.type = 1;
        this.modelTitle = '创建知识赛';
        this.formValidate.Dates = [
          this.timestampToTime(new Date().getTime() + 60 * 60 * 1000),
          this.timestampToTime(new Date().getTime() + 60 * 120 * 1000)
        ];
        this.startTimeChange(this.formValidate.Dates);
      }
    },
    saveModel() {
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          if (new Date(this.endDates).getTime() < new Date(this.startDates).getTime()) {
            this.$Message.warning('结束时间必须大于开始时间！');
            delete this.formValidate.Dates;
            this.loading = false;
            setTimeout(() => {
              this.loading = true;
            }, 300);
            return;
          }
          if (new Date(this.startDates).getTime() < new Date().getTime()) {
            this.$Message.warning('开始时间不能小于当前时间!');
            delete this.formValidate.Dates;
            this.loading = false;
            setTimeout(() => {
              this.loading = true;
            }, 300);
            return;
          }
          this.formValidate.matchMode = 3;
          let passObj = {
            ...this.formValidate,
            startDate: this.startDates + ':00',
            endDate: this.endDates + ':00',
            enrollStatus: '1'
          };
          delete passObj.Dates;
          passObj.extension = JSON.stringify({ needRelease: this.formValidate.needRelease });
          if (this.type === 1) {
            addcompetition(passObj)
              .then((data) => {
                if (data.code == 1) {
                  this.$Message.success('创建竞赛成功!');
                  this.showModel = false;
                  this.$emit('refreshSceneList');
                  this.formValidate = this.$options.data().formValidate;
                } else {
                  this.$Message.error(data.message);
                  this.loading = false;
                  setTimeout(() => {
                    this.loading = true;
                  });
                }
              })
              .catch((error) => {
                this.$Message.error('创建竞赛失败！');
                this.loading = false;
                setTimeout(() => {
                  this.loading = true;
                }, 300);
              });
          } else if (this.type === 2) {
            let modifyObj = {};
            modifyObj.id = this.formValidate.id;
            modifyObj.obj = passObj;
            modifycompetition(modifyObj).then((data) => {
              if (data.code == 1) {
                this.$Message.success('修改竞赛成功!');
                this.$emit('getList');
                this.showModel = false;
                this.formValidate = this.$options.data().formValidate;
              } else {
                this.$Message.warning(data.message);
                this.loading = false;
                setTimeout(() => {
                  this.loading = true;
                });
              }
            });
          }
        } else {
          //this.$Message.error('表单输入有误，请按页面提示输入!');
          this.loading = false;
          setTimeout(() => {
            this.loading = true;
          });
        }
      });
    },
    closeModel() {
      this.showModel = false;
    },
    handleFormatError() {
      this.showTip = true;
    },
    getImageUrl(file) {
      this.formValidate.iconPath = file.data;
      this.uploaderror = false;
      let src = this.formValidate.iconPath; //.slice(1)
      this.iconSrc = `../../Learn${src}`;
      //this.iconSrc = `http://172.18.100.1/Learn/${src}`;
    },
    handleBeforeUpload(file) {
      this.uploadList = this.$refs.upload.fileList;
      return true;
    },
    // 点击确认按钮关闭DatePicker组件时，标记状态
    clickOkBtn() {
      this.isClickOkBtn = true;
    },
    clickClearBtn() {
      this.formValidate.Dates = [];
      this.clickOkBtn();
    },
    changeDates(timeList) {
      this.formValidate.Dates = timeList;
    },
    // 切换DatePicker组件显示/关闭的状态
    switchOpenChange(isOpen) {
      this.$nextTick(() => {
        if (isOpen) {
          // 显示组件
          this.isClickOkBtn = false;
          this.originalTime = this.formValidate.Dates;
        } else {
          // 隐藏操作
          if (!this.isClickOkBtn) {
            // 不是通过点击确认按钮关闭DatePicker组件时，复原时间
            this.formValidate.Dates = this.originalTime;
            // // 上面时间复原后，数据虽然正确，但是子组件时间输入框和日历组件选中的日期都不对，所以需要用下面的代码手动设置一次
            // this.$refs['datePicker'].internalValue =
            //     [new Date(`${this.originalTime[0]}:00`),new Date(`${this.originalTime[1]}:00`)]
            // this.$refs['datePicker'].focusedDate = new Date(`${this.originalTime[0]}:00`)
          } else {
            this.startTimeChange(this.formValidate.Dates);
          }
        }
      });
    },
    startTimeChange(timeArr) {
      //设置开始时间
      if (timeArr.length > 0) {
        if (new Date(timeArr[0]).getTime() < new Date().getTime()) {
          //如果开始时间小于当前时间
          this.formValidate.Dates = [
            this.timestampToTime(new Date().getTime() + 60 * 60 * 1000),
            timeArr[1]
          ];
          this.startTimeChange(this.formValidate.Dates);
          return;
        }
        if (new Date(timeArr[1]).getTime() < new Date(timeArr[0]).getTime()) {
          //如果开始时间小于当前时间
          this.formValidate.Dates = [
            timeArr[0],
            this.timestampToTime(new Date(timeArr[0]).getTime() + 60 * 60 * 1000)
          ];
          this.startTimeChange(this.formValidate.Dates);
          return;
        }
        this.startDates = timeArr[0];
        this.endDates = timeArr[1];
      }
    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
      //      var s = date.getSeconds();
      return Y + M + D + h + m;
    }
  }
};
</script>

<style scoped>
.form-gourp {
  border: 1px solid var(--divider-color);
  margin-bottom: 20px;
  position: relative;
  padding: 10px;
}
.form-gourp:last-child {
  margin-bottom: 0;
}
.form-title {
  color: var(--default-color);
  font-weight: bold;
  position: absolute;
  position: absolute;
  top: -9px;
  left: 10px;
  background-color: var(--modal-bgcolor);
  display: inline-block;
  padding: 0 6px;
}
</style>
